<template>
	<view class="cz_box">
		<view class="cz_TabList">
			<view v-for="(item,index) in TabList" :key="index" @click="SelectTabFn(item)" :class="SelectTab.ID == item.ID?'cz_TabItem active':'cz_TabItem'">
				{{item.Label}}
			</view>
		</view>
		<view class="cz_Main">
			<!-- 运行 -->
			<block v-if="SelectTab.ID == 0">
				<view class="cz_OperateList">
					<block v-for="(item,index) in OperateList" :key="index">
						<!-- 清皮开关 -->
						<view
							v-if="item.ID == 1" 
							:class="TareStatus?'cz_OperateItem active':'cz_OperateItem'"
							@click="()=>{TareStatus = !TareStatus}"
						>
							<text>{{item.Label}}</text>
						</view>
						<!-- 自动累计开关 -->
						<view 
							v-if="item.ID == 2" 
							:class="GoodsSumStatus?'cz_OperateItem active':'cz_OperateItem'"
							@click="()=>{GoodsSumStatus = !GoodsSumStatus}"
						>
							<text>{{item.Label}}</text>
						</view>
						<view v-else @click="OperateFn(item)" class="cz_OperateItem">
							<text>{{item.Label}}</text>
						</view>
					</block>
				</view>
				<view class="cz_DataList">
					<view class="cz_DataStatus">
						<view class="cz_DataType_Label">
							重量状态
						</view>
						<view :style="`background-color:${WeightStatusBg[WeightStatus]};`" class="cz_DataType_Status"></view>
					</view>
					<view class="cz_DataType">
						<view class="cz_DataType_Label">
							标准
						</view>
						<view class="cz_DataItem">
							<view class="cz_DataLabel">
								下限
							</view>
							<view class="cz_DataValue">
								{{Floor}}
							</view>
						</view>
						<view class="cz_DataItem">
							<view class="cz_DataLabel">
								上限
							</view>
							<view class="cz_DataValue">
								{{Ceiling}}
							</view>
						</view>
					</view>
					<view class="cz_DataType">
						<view class="cz_DataType_Label">
							标准
						</view>
						<view class="cz_DataItem">
							<view class="cz_DataLabel">
								计数
							</view>
							<view class="cz_DataValue">
								{{GoodsNumber}}
							</view>
						</view>
						<view class="cz_DataItem">
							<view class="cz_DataLabel">
								累计
							</view>
							<view class="cz_DataValue">
								{{GoodsSumWeight}}
							</view>
						</view>
					</view>
				</view>
				<view class="cz_WeightData">
					<view class="cz_WeightPreview">
						<view class="cz_WeightPreviewItem">
							<view class="cz_WeightPreview_Label">
								毛重
							</view>
							<view class="cz_WeightPreview_Value">
								{{GrossWeight}}
							</view>
						</view>
						<view class="cz_WeightPreviewItem">
							<view class="cz_WeightPreview_Label">
								皮重
							</view>
							<view class="cz_WeightPreview_Value">
								{{Tare}}
							</view>
						</view>
						<view class="cz_WeightPreviewItem">
							<view class="cz_WeightPreview_Label">
								净重
							</view>
							<view class="cz_WeightPreview_Value">
								{{NetWeight}}
							</view>
						</view>
					</view>
					<view class="cz_WeightBar">
						<view class="cz_WeightMax">
							<view :style="`width:${WeighingPercentage}%;`" class="cz_Weighing"></view>
							<view class="cz_Weighing_text">
								{{WeighingPercentage}}/100
							</view>
						</view>
					</view>
					<view class="cz_uCharts">
						<view class="cz_uCharts_Canvas" >
							<qiun-data-charts 
							  type="mix"
							  :opts="opts"
							  :chartData="chartData"
							/>
						</view>
					</view>
				</view>
			</block>
			<!-- 设置 -->
			<block v-if="SelectTab.ID == 1">
				<view class="cz_SetGauge">
					<view class="cz_SetGaugeOperate">
						<view class="cz_Gauge_Adjust">
							<view class="cz_Gauge_Adjust_Label">
								称重标定
							</view>
							<view class="cz_Gauge_Adjust_Main">
								<view class="cz_Gauge_Adjust_Set">
									<view class="cz_Gauge_Adjust_SetItem">
										<view class="cz_Gauge_Adjust_SetItem_Input">
											<view class="cz_Gauge_Adjust_SetItem_Label">
												满量程
											</view>
											<input @input="(e)=>{MaxWeight = Number(e.detail.value)}" :value="MaxWeight" class="cz_Gauge_Adjust_SetItem_Value" type="number" />
										</view>
										<view class="cz_Gauge_Adjust_SetItem_Select">
											<view class="cz_Gauge_Adjust_SetItem_Label">
												精度
											</view>
											<uni-data-select
												class="cz_Gauge_Adjust_SetItem_Value"
												v-model="FixedIndex"
												:localdata="FixedList"
												@change="ChangeFixed"
											></uni-data-select>
										</view>
									</view>
									<view class="cz_Gauge_Adjust_SetItem">
										<view class="cz_Gauge_Adjust_SetItem_Input">
											<view class="cz_Gauge_Adjust_SetItem_Label">
												砝码值
											</view>
											<input @input="(e)=>{Standard = Number(e.detail.value)}" :value="Standard" class="cz_Gauge_Adjust_SetItem_Value" type="number" />
										</view>
										<view class="cz_Gauge_Adjust_SetItem_Select">
											<view class="cz_Gauge_Adjust_SetItem_Label">
												分度值
											</view>
											<uni-data-select
												class="cz_Gauge_Adjust_SetItem_Value"
												v-model="DivideIndex"
												:localdata="DivideList"
												@change="ChangeDivide"
											></uni-data-select>
										</view>
									</view>
								</view>
								<view class="cz_Gauge_Adjust_Operate">
									<button v-if="SetUp == 1&&!SetButtonStatus" @click="SetStandardSetUp1()" @ class="cz_Gauge_Adjust_Button">设置参数及校准零点</button>
									<button v-else class="cz_Gauge_Adjust_Button active">设置参数及校准零点</button>
									<button v-if="SetUp == 2&&!SetButtonStatus" @click="SetStandardSetUp2()" class="cz_Gauge_Adjust_Button">加载砝码完成校准</button>
									<button v-else class="cz_Gauge_Adjust_Button active">加载砝码完成校准</button>
								</view>
							</view>
						</view>
						<view class="cz_Gauge_MaxMin">
							<view class="cz_Gauge_Max">
								<input @input="(e)=>{Ceiling = Number(e.detail.value)}" :value="Ceiling" class="cz_Gauge_Max_Value" type="number" />
								<button @click="SubmitMaxMin('Ceiling')" class="cz_Gauge_Max_Submit">设置上限</button>
							</view>
							<view class="cz_Gauge_Min">
								<input @input="(e)=>{Floor = Number(e.detail.value)}" :value="Floor" class="cz_Gauge_Min_Value" type="number" />
								<button @click="SubmitMaxMin('Floor')" class="cz_Gauge_Min_Submit">设置下限</button>
							</view>
							<view class="cz_Gauge_Tare">
								<input @input="(e)=>{Tare = Number(e.detail.value)}" :value="Tare" class="cz_Gauge_Tare_Value" type="number" />
								<button @click="SubmitMaxMin('Tare')" class="cz_Gauge_Tare_Submit">设置皮重</button>
							</view>
						</view>
					</view>
					<view class="cz_GaugeBody">
						<WeightGauge :Fixed="FixedIndex" :Floor="Floor" :Ceiling="Ceiling" :MaxWeight="MaxWeight" :WeightValue="WeightValue"></WeightGauge>
					</view>
				</view>
			</block>
			<!-- 帮助 -->
			<block v-if="SelectTab.ID == 2">
			</block>
		</view>
		<!-- 暂不做 -->
		<view class="cz_ProgressBar">
			
		</view>
	</view>
</template>

<script>
import WeightGauge from "@/components/WeightGauge/WeightGauge.vue"
const COM = uni.requireNativePlugin("COM-Socket");
let uChartsInstance = {};
export default {
	data() {
		return {
			cWidth: 600,
			cHeight: 400,
			TabList:[
				{
					Label:"运行",
					ID:0
				},
				{
					Label:"设置",
					ID:1
				},
				{
					Label:"帮助",
					ID:2
				},
			],
			SelectTab:{},
			OperateList:[
				{
					Label:"置零",
					ID:0
				},
				{
					Label:"清皮",
					ID:1
				},
				{
					Label:"自动累计",
					ID:2
				},
				{
					Label:"手动累计",
					ID:3
				},
				{
					Label:"累计清除",
					ID:4
				},
			],
			Floor:0,	//下限
			Ceiling:0,	//上限
			GoodsNumber:0,	//计数
			GoodsSumWeight:0,//累计重量
			GoodsSumStatus:false,	//自动累计状态
			MaxRange:0,		//最大量程
			// --------------------- 不固定值
			GrossWeight:0,	//毛重
			Tare:0,			//皮重
			TareStatus:false,	//清皮状态
			NetWeight:0,		//净重
			// --------------------- 稳定后的值
			SteadyGrossWeight:0,	//稳定的毛重
			SteadyNetWeight:0,		//稳定的皮重
			// ------------------------- 折线图 start ------------------------------
			uEcharsLength:5,	//折线图数据长度
			opts: {
				color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
				padding: [15,35,0,30],
				enableScroll: false,
				legend: {},
				xAxis: {
				  disableGrid: true,
				  title: "单位：件"
				},
				yAxis: {
				  // gridType: "dash",
				  // dashLength: 2,
					disabled: false,
					disableGrid: false,
					splitNumber: 5,
					gridType: "dash",
					dashLength: 4,
					gridColor: "#CCCCCC",
					padding: 10,
					showTitle: true,
					data: [
						{
						  position: "left",
						  title: "实时重量折线图"
						}
					  ]
				},
				extra: {
					mix: {
						column: {
							width: 20
						}
				   }
				},
				animation: false, // 关闭动画
				update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
				duration: 0, // 关闭动画过度
			},
			chartData:{
				categories: [],
				series: [
					{
						name: "重量",
						type: "line",
						color: "#2fc25b",
						data: []
					}
				]
			},
			// ------------------------------ 折线图 end --------------------------
			defaultDevic:"/dev/ttyS2",	//初始串口路径
			defaultBtl:9600,		//初始比特率
			// ------------------------------ 调试模式参数 start -------------------------
			DevicPathList:[],	//串口路径列表
			DevicPathIndex:0,	//当前选择串口
			DevicPath:"",	//当前串口
			BtlIndex:3,
			BtlList:[{value:0,text:1200},{value:1,text:2400},{value:2,text:4800},{value:3,text:9600},{value:4,text:14400},{value:5,text:19200},{value:6,text:38400},{value:7,text:115200}],
			Btl:0,				//当前
			// ------------------------------ 调试模式参数 end ----------------------
			DeviceStatus:false,		//设备是否连接
			PollingStatus:false,	//轮询状态
			OperateStatus:false,	//当前是否还有其他指令在发送
			GetWeightTimeStatus:false,	//获取重量的指令循环
			// ------------------------------- 答应数据 ------------------------------
			ComValue:'',		//初始数据
			WeightStatus:1,		//秤状态
			WeightValue:0,		//物品重量
			Post:'',			//指令
			Promise:'',			//指令答应
			// ------------------------------- 存储数据 -------------------------------
			// sqlLit 存储总数据
			// ----------------------------- 设置页参数 ---------------------------------
			// ----------------------- 称重标定 start ------------------
			SetUp:1,
			SetButtonStatus:false,
			// 量程
			MaxWeight:10000,
			// 精度
			Fixed:0,
			FixedIndex:0,
			FixedList:[
				{value:0,text:'0',OperateValue:0},
				{value:1,text:'0.0',OperateValue:1},
				{value:2,text:'0.00',OperateValue:2},
				{value:3,text:'0.000',OperateValue:3},
			],
			// 砝码值
			Standard:5000,
			// 分度值
			Divide:1,
			DivideIndex:0,
			DivideList:[
				{value:0,text:'1'},
				{value:1,text:'2'},
				{value:2,text:'5'},
			],
			// ----------------------- 称重标定 over ------------------ 
		};
	},
	components:{
		WeightGauge:WeightGauge
	},
	watch:{
		TareStatus:{
			immediate:true,
			handler(){
				// 开启清皮开关
				if(this.TareStatus){
					this.Tare = 0
				}else{
					this.Tare = uni.getStorageSync("Tare")?uni.getStorageSync("Tare"):0
				}
			}
		},
		// 数据解构
		ComValue:{
			immediate:true,
			handler(){
				if(!this.ComValue) return
				if(this.ComValue.substring(0,2) == 'ST'){
					switch(this.ComValue.split(',')[1]){
						case '0':
							this.WeightStatus = 0
							break;
						case '1':
							this.WeightStatus = 1
							break;
					}
					switch(this.ComValue.split(',')[2]){
						case '2':
							this.WeightStatus = 2
							break;
					}
					// 重量 = 符号（第 6 位） + 重量（6位以后）
					let symbol = this.ComValue.split(',')[0].substring(2,3)
					let Value = Number(this.ComValue.split(',')[0].substring(3,))
					this.WeightValue = Number(symbol + Value)
					// ------------------ 累计 及 计数 ------------------
					// 当重量稳定(且值不为0)后自动记录稳定值
					if(this.WeightStatus == 1&&this.WeightValue){
						this.SteadyGrossWeight = this.WeightValue
						this.SteadyNetWeight = this.WeightValue - Number(this.Tare)
					}
					// 当累计状态开启时且上一个值不为零,下一个值为零,(且有稳定值)时,自动累计一,且更新折线图
					if(this.GoodsSumStatus&&this.GrossWeight&&!this.WeightValue&&this.SteadyNetWeight){
						this.GoodsNumber++
						this.GoodsSumWeight += this.SteadyNetWeight
						this.getServerData()
						// ------------------ 累计后清零 -------------------
						this.SteadyGrossWeight = 0
						this.SteadyNetWeight = 0
					}
					// -----------------  设置 毛重 净重 ----------------
					this.GrossWeight = this.WeightValue
					this.NetWeight = this.WeightValue - Number(this.Tare)
				}else{
					// 指令
					this.Promise = this.ComValue
				}
			}
		}
	},
	computed:{
		// 进度条
		WeighingPercentage(){
			if(this.MaxRange){
				return this.NetWeight / this.MaxRange * 100
			}else{
				return 0
			}
 		}
	},
	onShow() {
		this.$nextTick(async ()=>{
			// 初始化值
			await this.InitValue()
			this.StartDevice()
		})
	},
	onReady() {
		this.getServerData();
	},
	onHide() {
		this.OnClose()
		this.GetWeightTimeStatus = false
	},
	methods:{
		// ----------------------------- 设置 -------------------------------
		SubmitMaxMin(type){
			switch(type){
				// 上限
				case 'Ceiling':
					uni.setStorageSync("Ceiling",this.Ceiling)
					break;
				// 下限
				case 'Floor':
					uni.setStorageSync("Floor",this.Floor) 
					break;
				// 皮重
				case 'Tare':
					uni.setStorageSync("Tare",this.Tare)	//皮重
					break;
			}
			this.$forceUpdate()
		},
		ChangeFixed(e){
			this.FixedIndex = e
			this.Fixed = this.FixedList[e].OperateValue
		},
		ChangeDivide(e){
			this.DivideIndex = e
			this.Divide = this.DivideList[e].text
		},
		// ----------------------------- 设置 -------------------------------
		InitValue(){
			return new Promise((resolve,reject)=>{
				this.SelectTab = this.TabList[1]
				// 皮重
				this.Tare = uni.getStorageSync("Tare")?Number(uni.getStorageSync("Tare")):0
				// 串口路径
				this.DevicPath = uni.getStorageSync("DevicPath")?uni.getStorageSync("DevicPath"):""
				// 比特率
				this.Btl = uni.getStorageSync("Btl")?uni.getStorageSync("Btl"):0
				// 上限
				this.Ceiling = uni.getStorageSync("Ceiling")?Number(uni.getStorageSync("Ceiling")):0
				// 下限
				this.Floor = uni.getStorageSync("Floor")?Number(uni.getStorageSync("Floor")):0
				
				const res = uni.getStorageSync("CALValue")
				console.log(res);
				// 最大量程
				this.MaxWeight = Number(res.split(",")[0])
				// 砝码值
				this.Standard = Number(res.split(",")[1])
				// 精度
				switch(Number(res.split(",")[2])){
					case 0:
						this.Fixed = 0
						this.FixedIndex = 0
						break;
					case 1:
						this.Fixed = 1
						this.FixedIndex = 1
						break;
					case 2:
						this.Fixed = 2
						this.FixedIndex = 2
						break;
					case 3:
						this.Fixed = 3
						this.FixedIndex = 3
						break;
				}
				// 分度
				switch(Number(res.split(",")[3])){
					case 0:
						this.Divide = 1
						this.DivideIndex = 0
						break;
					case 1:
						this.Divide = 2
						this.DivideIndex = 1
						break;
					case 2:
						this.Divide = 5
						this.DivideIndex = 2
						break;
				}
				resolve()
			})
		},
		OperateFn(data){
			if(!this.COMOpen){
				uni.showToast({
					title:"请先打开串口",
					icon:"none"
				})
				return 
			}
			if(this.OperateStatus) return
			this.GetWeightTimeStatus = false
			this.OperateStatus = true
			setTimeout(async ()=>{
				switch(data.ID){
					case -1:
						// 发送过后，需要等待秤稳定后（15s），再去读
						const Resvalue = await this.OnSendStandard(data.Operate)
						if(Resvalue.code == 200){
							uni.showToast({
								title:Resvalue.title,
								icon:'none'
							})
						}else if(Resvalue.code == 201){
							uni.showModal({
								title:"超时",
								content:"请不要触碰秤，使其在稳定状态下运行"
							})
						}
						setTimeout(()=>{
							this.OperateStatus = false
							// 指令读取完成后再开启读重量
							this.GetWeightTimeStatus = true
							this.SettimeoutSendGetWeight()
						},5000)
						break;
					// 清零
					case 0:
						// 操作时先停止发送指令，防止多个读取器在读( 0.2 s后 再发送指令)
						await this.OnSend("AT+ZERO")
						this.OperateStatus = false
						// 指令读取完成后再开启读重量
						this.GetWeightTimeStatus = true
						this.SettimeoutSendGetWeight()
						break;
					// 清皮
					case 1:
						break;
					// 自动累计
					case 2:
						break;
					// 手动累计
					case 3:
						this.SteadyGrossWeight = this.WeightValue
						this.SteadyNetWeight = this.WeightValue - Number(this.Tare)
						// 当上一个值不为零,下一个值为零,(且有稳定值)时,自动累计一,且更新折线图
						this.GoodsNumber++
						this.GoodsSumWeight += this.SteadyNetWeight
						this.getServerData()
						// ------------------ 累计后清零 -------------------
						this.SteadyGrossWeight = 0
						this.SteadyNetWeight = 0
						break;
					case 4:
					// 累计清除 (上下限)
						this.GoodsNumber = 0
						this.GoodsSumWeight = 0
						let newChartData = JSON.parse(JSON.stringify(this.chartData))
						newChartData.categories = [0]
						newChartData.series[0].data = [0]
						this.chartData = newChartData
						break;
				}
			},200)
		},
		SelectTabFn(data){
			this.SelectTab = data
		},
		// 折线图更新
		getServerData() {
			let newChartData = JSON.parse(JSON.stringify(this.chartData))
			let newCategories = newChartData.categories
			let newData = newChartData.series[0].data
			newCategories.push(this.GoodsNumber)
			newData.push(this.SteadyNetWeight)
			if(newCategories.length > this.uEcharsLength){
				newCategories.shift()
				newData.shift()
			}
			this.chartData = newChartData
		},
		// --------------------------------- 开启设备 start --------------------
		// 开启设备
		async StartDevice(){
			// 第一步 连接串口
			await this.GoBind()
			// 第二步 发送测试指令，查看当前串口设备是否正常
			await this.SendTest()
			// 第三步 检测是否第一次启动，第一次启动，发送获取参数
			if(!uni.getStorageSync("FirstOpen")){
				await this.FirstOpen()
			}
			// 第四步 开始轮询发送 请求重量指令
			// 设置轮询状态（true 为当前正在轮询）
			this.PollingStatus = true
			this.PollingSend()
		},
		// 会打断轮询的操作 分为 一答一回，一答多回(特殊操作)
		// 一答一回
		OnePostOneRespond(Operate){
			return new Promise(async(reslove,reject)=>{
				let Fn = () => {
					return new Promise(async (reslove1,reject1)=>{
						await this.OnSend(Operate)
						const res = await this.OnListen()
						reslove1(res)
					})
				}
				const res = await this.StopPollingAndSend(Fn)
				reslove(res)
			})
		},
		// 设置参数并校零
		async SetStandardSetUp1(){
			if(this.MaxWeight.length > 6){
				return this.TipList.push('满量程不可大于6位数')
			}
			if(this.Standard.length > 6){
				return this.TipList.push('砝码值不可大于6位数')
			}
			this.SetButtonStatus = true
			let Fn = () =>{
				return new Promise(async(reslove,reject)=>{
					let SendValue = 'AT+CAL='
					let MaxWeight = this.MaxWeight
					let Standard = this.Standard
					let Fixed = this.Fixed
					let Divide = this.Divide
					for(let i = 0;i < (6 - this.MaxWeight.toString().length);i++){
						MaxWeight = '0' + MaxWeight
					}
					for(let j = 0;j < (6 - this.Standard.toString().length);j++){
						Standard = '0' + Standard
					}
					SendValue = SendValue + `${MaxWeight},${Standard},${Fixed},${Divide}`
					uni.setStorageSync("CALValue",`${MaxWeight},${Standard},${Fixed},${Divide}`)
					// 一发
					await this.OnSend(SendValue)
					// 第一答
					const Value1 = await this.OnListen()
					console.log(Value1);
					if(Value1.data == "OK"){
						uni.showToast({
							title:"接受到指令",
							icon:'none'
						})
					}
					// 第二答
					const Value2 = await this.OnListen()
					console.log(Value2);
					if(Value2.data == "->"){
						uni.showToast({
							title:"正在获取稳定的零点值",
							icon:'none'
						})
					}
					// 第三答
					const Value3 = await this.OnListen()
					console.log(Value3);
					if(Value3.data == "OK"){
						uni.showToast({
							title:"零点获取成功",
							icon:'none'
						})
					}
					this.SetUp = 2
					reslove()
				})
			}
			const res = await this.StopPollingAndSend(Fn)
			this.SetButtonStatus = false
		},
		// 校准
		async SetStandardSetUp2(){
			this.SetButtonStatus = true
			let Fn = () =>{
				return new Promise(async (reslove,reject)=>{
					// 一发
					await this.OnSend('AT+CALW')
					// 第一答
					const Value1 = await this.OnListen()
					if(Value1.data == "OK"){
						uni.showToast({
							title:"接受到指令",
							icon:'none'
						})
					}
					console.log(Value1);
					// 第二答
					const Value2 = await this.OnListen()
					if(Value2.data == "->"){
						uni.showToast({
							title:"正在获取稳定的校准点值",
							icon:'none'
						})
					}
					console.log(Value2);
					// 第三答
					const Value3 = await this.OnListen()
					if(Value3.data == "OK"){
						uni.showToast({
							title:"校准成功",
							icon:'none'
						})
					}
					console.log(Value3);
					this.SetUp = 1
					reslove()
				})
			}
			const res = await this.StopPollingAndSend(Fn)
			this.SetButtonStatus = false
		},
		// 去连接
		GoBind(){
			return new Promise(async(reslove,reject)=>{
				let DevicPath = this.DevicPath?this.DevicPath:this.defaultDevic
				let Btl = this.Btl?this.Btl:this.defaultBtl
				if(!DevicPath||!Btl){
					return uni.showToast({
						title:'请先设置串口和波特率',
						icon:'none'
					})
				}
				const res = await this.OnBind(DevicPath,Btl)
				if(res.code == 200){
					console.log(res.data)
				}
				reslove(res)
			})
			
		},
		// 发送测试指令(并接受回自己的发送指令的答应)
		SendTest(){
			return new Promise(async(reslove,reject)=>{
				const res = await this.OnePostOneRespond("AT")
				if(res.code == 200){
					console.log("设备正常")
					this.DeviceStatus = true
				}
				reslove()
			})
		},
		FirstOpen(){
			return new Promise(async (reslove,reject)=>{
				// 发送初始化指令
				let res1 = await this.OnePostOneRespond("AT+AUTO=0")
				// 获取当前校准参数(根据校准参数获取到最大值)
				let res = await this.OnePostOneRespond("AT+CAL?")
				console.log(res);
				res = res.data.
				uni.setStorageSync("CALValue",res)
				// 根据校准参数设置 最大量程 砝码值 分度值 精度值
				this.MaxWeight = Number(res.split(",")[0])
				this.Standard = Number(res.split(",")[1])
				switch(Number(res.split(",")[2])){
					case 0:
						this.Fixed = 0
						this.FixedIndex = 0
						break;
					case 1:
						this.Fixed = 1
						this.FixedIndex = 1
						break;
					case 2:
						this.Fixed = 2
						this.FixedIndex = 2
						break;
					case 3:
						this.Fixed = 3
						this.FixedIndex = 3
						break;
				}
				switch(Number(res.split(",")[3])){
					case 0:
						this.Divide = 1
						this.DivideIndex = 0
						break;
					case 1:
						this.Divide = 2
						this.DivideIndex = 1
						break;
					case 2:
						this.Divide = 5
						this.DivideIndex = 2
						break;
				}
				uni.setStorageSync("FirstOpen",true)
				reslove()
			})
		},
		// 停止轮询并发送指令
		StopPollingAndSend(fn){
			return new Promise(async(reslove,reject)=>{
				this.PollingStatus = false
				setTimeout(async()=>{
					// 关闭轮询
					const res = await fn()
					// 开启轮询
					this.PollingStatus = true
					this.PollingSend()
					reslove(res)
				},500)
			})
		},
		// 轮询
		async PollingSend(){
			// 当 设备正常 时才可以轮询
			if(!this.DeviceStatus) return
			// 如果 轮询状态被设置为 false
			if(!this.PollingStatus) return
			const res = await this.delayedSend()
			this.ComValue = res.data
			this.PollingSend()
		},
		// 延时请求并读取
		delayedSend(){
			return new Promise(async(reslove,reject)=>{
				setTimeout(async()=>{
					// 当 设备正常 时才可以轮询
					if(!this.DeviceStatus) return
					// 如果 轮询状态被设置为 false
					if(!this.PollingStatus) return
					await this.OnSend("AT+WEI")
					const res = await this.OnListen()
					reslove(res)
				},100)
			})
		},
		// --------------------------------- 开启设备 end ----------------------
		//获取串口列表
		GetComList(){
			return new Promise((reslove,reject)=>{
				COM.SerialPortListExample(e=>{
					reslove(e)
				})
			})
		},
		// 设置路径
		SetDVPath(Path){
			this.DevicPath = Path
		},
		// 连接
		OnBind(DevicPath,Btl){
			return new Promise(async(reslove,reject)=>{
				let Fn = () =>{
					return new Promise((reslove,reject)=>{
						COM.Bind(DevicPath,this.Btl,e=>{
							reslove(e)
						})
					})
				}
				const res = await this.TryCatch(Fn)
				reslove(res)
			})
		},
		// 发送指令
		OnSend(Operate){
			return new Promise(async(reslove,reject)=>{
				let Fn = () =>{
					return new Promise((reslove,reject)=>{
						COM.Send(Operate,(e)=>{
							reslove(e)
						})
					})
				}
				const res = await this.TryCatch(Fn)
				reslove(res)
			})
		},
		// 由于一次只读一个字节，将其拼装为完整数据在返回
		OnListen(){
			return new Promise(async(reslove,reject)=>{
				let Complete = ""
				let LRIndex = null;
				let LNIndex = null;
				let data = {}
				for(let i = 0;true;i++){
					let Fn = () =>{
						return new Promise((reslove,reject)=>{
							COM.ListenOneBty((e) => {
								reslove(e)
							})
						})
					}
					const res = await this.TryCatch(Fn)
					Complete += res.data
					LRIndex = Complete.indexOf("\r")
					LNIndex = Complete.indexOf("\n")
					if(LRIndex != -1&&LNIndex != -1){
						Complete = Complete.substring(0,LRIndex)
						data = {
							code:200,
							data:Complete
						}
						break;
					}
				}
				reslove(data)
			})
		},
		// 断开串口
		OnClose(){
			return new Promise(async(reslove,reject)=>{
				let Fn = () => {
					return new Promise((reslove,reject)=>{
						COM.Close(e => {
							reslove(e)
						})
					})
				}
				const res = await this.TryCatch(Fn)
				reslove(res)
			})
		},
		TryCatch(fn){
			return new Promise(async(reslove,reject)=>{
				const res = await fn()
				if(res.code == 400){
					uni.showModal({
						title:"错误",
						content:res.data
					})
					reject()
				}else if(res.code == 200){
					reslove(res)
				}
			})
		}
	}
}
</script>

<style lang="scss">
.cz_box{
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	overflow: hidden;
	.cz_TabList{
		width: 100%;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		background-color:$cz_BackGround;
		.cz_TabItem{
			padding:calc(16rpx + 24rpx) calc(50rpx + 24rpx);
			color: #fff;
		}
		.active{
			background-color: #fff;
			color: #000;
		}
	}
	.cz_Main{
		margin-top:24rpx;
		flex: 1;
		width: 100%;
		display: flex;
		align-items: center;
		overflow: hidden;
		.cz_SetGauge{
			width: 100%;
			height: 100%;
			display: grid;
			grid-template-columns: repeat(2,1fr);
			grid-column-gap: 24rpx;
			box-sizing: border-box;
			.cz_SetGaugeOperate{
				width: 100%;
				height: 100%;
				display: grid;
				grid-template-rows: 1fr 400rpx;
				grid-row-gap: 24rpx;
				box-sizing: border-box;
				.cz_Gauge_Adjust{
					width: 100%;
					height: 100%;
					padding:24rpx;
					box-sizing: border-box;
					background-color:$cz_BackGround;
					.cz_Gauge_Adjust_Label{
						color:#e5e5e5;
						font-size: 32rpx;
					}
					.cz_Gauge_Adjust_Main{
						width: 100%;
						.cz_Gauge_Adjust_Set{
							width: 100%;
							.cz_Gauge_Adjust_SetItem{
								display: grid;
								grid-template-columns: repeat(2,1fr);
								grid-column-gap: 24rpx;
								.cz_Gauge_Adjust_SetItem_Input{
									.cz_Gauge_Adjust_SetItem_Label{
									}
									.cz_Gauge_Adjust_SetItem_Value{
										background-color: #fff;
										height: 70rpx;
										line-height: 70rpx;
									}
								}
								.cz_Gauge_Adjust_SetItem_Select{
									.cz_Gauge_Adjust_SetItem_Label{
										
									}
									.cz_Gauge_Adjust_SetItem_Value{
										background-color: #fff;
										height: 70rpx;
										line-height: 70rpx;
									}
								}
							}
						}
						.cz_Gauge_Adjust_Operate{
							margin-top:24rpx;
							width: 100%;
							display: grid;
							grid-template-columns: repeat(2,1fr);
							grid-column-gap:24rpx;
							.cz_Gauge_Adjust_Button{
								width: 100%;
								padding:24rpx 0;
							}
							.active{
								background-color: #CCCCCC;
								color: #787878;
							}
						}
					}
				}
				.cz_Gauge_MaxMin{
					width: 100%;
					height: 100%;
					display: grid;
					grid-template-columns: repeat(3,1fr);
					grid-column-gap: 24rpx;
					.cz_Gauge_Max{
						display: flex;
						flex-direction: column;
						align-item: center;
						justify-content: space-around;
						background-color:$cz_BackGround;
						padding:24rpx;
						box-sizing: border-box;
						.cz_Gauge_Max_Value{
							padding:24rpx 0;
							width: 100%;
							background-color: #fff;
						}
						.cz_Gauge_Max_Submit{
							width: 100%;
							padding:24rpx 0;
						}
					}
					.cz_Gauge_Min{
						display: flex;
						flex-direction: column;
						align-item: center;
						justify-content: space-around;
						background-color:$cz_BackGround;
						padding:24rpx;
						box-sizing: border-box;
						.cz_Gauge_Min_Value{
							padding:24rpx 0;
							background-color: #fff;
							width: 100%;
						}
						.cz_Gauge_Min_Submit{
							width: 100%;
							padding:24rpx 0;
							box-sizing: border-box;
						}
					}
					.cz_Gauge_Tare{
						display: flex;
						flex-direction: column;
						align-item: center;
						justify-content: space-around;
						background-color:$cz_BackGround;
						padding:24rpx;
						box-sizing: border-box;
						.cz_Gauge_Tare_Value{
							padding:24rpx 0;
							background-color: #fff;
							width: 100%;
						}
						.cz_Gauge_Tare_Submit{
							width: 100%;
							padding:24rpx 0;
							box-sizing: border-box;
						}
					}
				}
			}
			.cz_GaugeBody{
				padding:24rpx;
				box-sizing: border-box;
				width: 100%;
				height: 100%;
				background-color:$cz_BackGround;
			}
		}
		.cz_OperateList{
			padding: 24rpx;
			height: 100%;
			display: grid;
			grid-template-rows: repeat(auto-fit,minmax(100rpx,1fr));
			grid-row-gap: 24rpx;
			background-color:$cz_BackGround;
			box-sizing: border-box;
			.cz_OperateItem{
				padding:0 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				line-height: 100%;
				border: 1rpx solid #000;
				background-color: #f5f5f5;
			}
			.active{
				background-color: #9BABBA;
			}
			.cz_OperateItem:active{
				background-color: #9BABBA;
			}
		}
		.cz_DataList{
			margin:0 24rpx;
			width: 300rpx;
			height: 100%;
			padding: 24rpx;
			box-sizing: border-box;
			background-color:$cz_BackGround;
			.cz_DataStatus{
				width: 100%;
				display: flex;
				justify-content: space-between;
				margin-bottom:36rpx;
				.cz_DataType_Label{
					width: 100%;
					font-size: 32rpx;
					color:#e1e1e1;
				}
				.cz_DataType_Status{
					width: 40rpx;
					height: 40rpx;
					border-radius: 50%;
					background-color:#18FD29;
				}
			}
			.cz_DataType{
				width: 100%;
				display: flex;
				flex-direction: column;
				margin-bottom:36rpx;
				.cz_DataType_Label{
					width: 100%;
					font-size: 32rpx;
					color:#e1e1e1;
				}
				.cz_DataItem{
					width: 100%;
					display: flex;
					flex-direction: column;
					align-items: center;
					.cz_DataLabel{
						width: 100%;
						margin-bottom:24rpx;
					}
					.cz_DataValue{
						width: 100%;
						border: 1rpx solid #fff;
					}
				}
			}
		}
		.cz_WeightData{
			flex: 1;
			height: 100%;
			padding:0 24rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			.cz_WeightPreview{
				width: 100%;
				display: grid;
				grid-template-columns: repeat(3,1fr);
				grid-column-gap:24rpx;
				.cz_WeightPreviewItem{
					padding:30rpx;
					background-color: #000;
					color: #fff;
					font-weight: 700;
					font-size: 45rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					.cz_WeightPreview_Value{
						font-size:60rpx;
					}
				}
			}
			.cz_WeightBar{
				height: 50rpx;
				margin:24rpx 0;
				width:100%;
				.cz_WeightMax{
					position: relative;
					height: 100%;
					width: 100%;
					background-color: #9BABBA;
					.cz_Weighing{
						height: 100%;
						background-color: #18FD29;
					}
					.cz_Weighing_text{
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						text-align: center;
						line-height:50rpx;
						color: #000;
					}
				}
			}
			.cz_uCharts{
				flex: 1;
				width: 100%;
				.cz_uCharts_Canvas{
					height: 100%;
					width: 100%;
				}
			}
		}
	}
}
</style>
